package com.example.handler;

import com.example.util.PropertiesUtil;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 加载静态文件
 */
public class StaticHandler implements HttpHandler {

    private static final Logger log = Logger.getLogger(StaticHandler.class.getCanonicalName());
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        File file = new File(PropertiesUtil.staticDir+httpExchange.getRequestURI().getPath()+".html");
        if(file.exists() && file.isFile()){
            httpExchange.sendResponseHeaders(200,file.length());
            OutputStream os = httpExchange.getResponseBody();
            try (FileInputStream fis = new FileInputStream(file)) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                }
            }
        }else {
            String response = "File not found";
            httpExchange.sendResponseHeaders(404, response.length());
            try (OutputStream os = httpExchange.getResponseBody()) {
                os.write(response.getBytes());
            }
        }
    }
}
